﻿using Microsoft.Data.SqlClient;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Text;

namespace Fdb.SqlServer
{
    ///<summary>
    ///数据库操作基础类(数据层)。
    /// </summary>
    public class SqlDbHelper
    {
        #region 配置数据库连接字符串

        private string _connectionString = "";

        private readonly string RETURNVALUE = "RETURNVALUE";

        public string ConnectionString
        {
            set
            {
                this._connectionString = value;
            }
            get
            {
                return this._connectionString;
            }
        }

        #endregion 配置数据库连接字符串

        #region 执行简单SQL语句

        /// <summary>
        /// 执行sql语句
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public int ExecuteSQL(string sql)
        {
            using (SqlConnection connection = new SqlConnection(ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand(sql, connection))
                {
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }

                    finally
                    {
                        if (cmd != null)
                        {
                            cmd.Dispose();
                        }
                        if (connection != null)
                        {
                            connection.Close();
                            connection.Dispose();
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 执行事务
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="prams"></param>
        /// <returns></returns>
        public int ExcuteTransactionSQL(string sql, SqlParameter[] prams)
        {
            using (SqlConnection connection = new SqlConnection(ConnectionString))
            {
                int val = -1;
                connection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = connection;
                SqlTransaction transaction = connection.BeginTransaction();
                cmd.Transaction = transaction;
                try
                {
                    cmd.CommandText = sql;
                    val = cmd.ExecuteNonQuery();
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    throw ex;
                }

                finally
                {
                    if (cmd != null)
                    {
                        cmd.Dispose();
                    }
                    if (connection != null)
                    {
                        connection.Close();
                        connection.Dispose();
                    }
                }

                return val;
            }
        }

        /// <summary>
        /// 执行事务的sql
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="prams"></param>
        /// <param name="transaction"></param>
        /// <returns></returns>
        public int ExcuteTransactionSQL(string sql, SqlParameter[] prams, DbTransaction transaction)
        {
            SqlTransaction sqlTransaction = (SqlTransaction)transaction;
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, sqlTransaction.Connection, sqlTransaction, sql, prams);

            int val = -1;

            try
            {
                cmd.CommandText = sql;
                val = cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                //if (cmd.Connection != null)
                //{
                //    cmd.Connection.Close();
                //    cmd.Connection.Dispose();
                //}

                //sqlTransaction.Rollback();
                throw ex;
            }

            finally
            {
                if (cmd != null)
                {
                    cmd.Dispose();
                }
            }

            return val;
        }

        public object GetSingle(string SQLString)
        {
            using (SqlConnection connection = new SqlConnection(ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }

                    finally
                    {
                        if (cmd != null)
                        {
                            cmd.Dispose();
                        }
                        if (connection != null)
                        {
                            connection.Close();
                            connection.Dispose();
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 执行SQL语句
        /// </summary>
        /// <param name="sql">SQL语句</param>  
        /// <param name="dataReader">返回DataReader对象</param>
        public void ExecuteSQL(string sql, out SqlDataReader dataReader)
        {
            try
            {
                ExecuteSQL(sql, null, out dataReader);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 执行SQL语句
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="prams"></param>
        /// <param name="dataReader"></param>
        public void ExecuteSQL(string sql, SqlParameter[] prams, out SqlDataReader dataReader)
        {
            ///创建Command
            using (SqlCommand cmd = CreateSqlCommand(sql, prams))
            {
                using (SqlConnection connection = new SqlConnection(ConnectionString))
                {
                    cmd.Connection = connection;
                    connection.Open();

                    try
                    {
                        dataReader = cmd.ExecuteReader();
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }

                    finally
                    {
                        if (cmd != null)
                        {
                            cmd.Dispose();
                        }
                        if (connection != null)
                        {
                            connection.Close();
                            connection.Dispose();
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 创建一个SqlCommand对象以此来执行SQL语句
        /// </summary>
        /// <param name="sql">SQL语句</param>
        /// <param name="prams">SQL语句所需参数</param>
        /// <returns>返回OleDbCommand对象</returns>
        private SqlCommand CreateSqlCommand(string sql, SqlParameter[] prams)
        {
            using (SqlCommand cmd = new SqlCommand(sql))
            {
                try
                {
                    ///添加到语句的参数
                    if (prams != null)
                    {
                        foreach (SqlParameter parameter in prams)
                        {
                            cmd.Parameters.Add(parameter);
                        }
                    }

                    //返回创建的SqlCommand对象
                    return cmd;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

        }

        /// <summary>
        /// 获得ds
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="dataSet"></param>
        public void ExecuteSQL(string sql, ref DataSet dataSet)
        {
            using (SqlConnection connection = new SqlConnection(ConnectionString))
            {
                DataSet ds = new DataSet();
                SqlDataAdapter adapter = new SqlDataAdapter();
                try
                {
                    connection.Open();
                    adapter = new SqlDataAdapter(sql, connection);
                    adapter.Fill(dataSet, "ds");
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                finally
                {
                    if (connection != null)
                    {
                        connection.Close();
                        connection.Dispose();
                    }
                }
            }
        }

        #endregion

        #region 带参数的SQL

        /// <summary>
        /// 执行带参数的sql
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="cmdParms"></param>
        /// <returns></returns>
        public int ExecuteSQL(string sql, SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, sql, cmdParms);
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        return rows;
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }

                    finally
                    {
                        if (cmd != null)
                        {
                            cmd.Dispose();
                        }
                        if (connection != null)
                        {
                            connection.Close();
                            connection.Dispose();
                        }
                    }
                }
            }
        }

        public void ExecuteSqlTran(Hashtable SQLStringList)
        {
            using (SqlConnection connection = new SqlConnection(ConnectionString))
            {
                connection.Open();
                using (SqlTransaction trans = connection.BeginTransaction())
                {
                    SqlCommand cmd = new SqlCommand();
                    try
                    {
                        //循环
                        foreach (DictionaryEntry myDE in SQLStringList)
                        {
                            string sql = myDE.Key.ToString();
                            SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;
                            PrepareCommand(cmd, connection, trans, sql, cmdParms);
                            int val = cmd.ExecuteNonQuery();
                            cmd.Parameters.Clear();
                        }
                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        throw ex;
                    }

                    finally
                    {
                        if (cmd != null)
                        {
                            cmd.Dispose();
                        }
                        if (connection != null)
                        {
                            connection.Close();
                            connection.Dispose();
                        }
                    }
                }
            }
        }

        public object GetSingle(string SQLString, DbParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        object obj = cmd.ExecuteScalar();
                        cmd.Parameters.Clear();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }

                    finally
                    {
                        if (cmd != null)
                        {
                            cmd.Dispose();
                        }
                        if (connection != null)
                        {
                            connection.Close();
                            connection.Dispose();
                        }
                    }
                }
            }
        }

        public void GetDataSet(string SQLString, DbParameter[] cmdParms, ref DataSet dataSet)
        {
            using (SqlConnection connection = new SqlConnection(ConnectionString))
            {
                SqlCommand cmd = new SqlCommand();
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    try
                    {
                        da.Fill(dataSet, "ds");
                        cmd.Parameters.Clear();
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }

                    finally
                    {
                        if (cmd != null)
                        {
                            cmd.Dispose();
                        }
                        if (connection != null)
                        {
                            connection.Close();
                            connection.Dispose();
                        }
                    }
                }
            }
        }

        private void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string sql, DbParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = sql;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;//cmdType;
            if (cmdParms != null)
            {
                foreach (SqlParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }
        #endregion

        #region 执行存储过程
        public int RunProcedureExecuteSql(string storeProcName, DbParameter[] parameters)
        {
            using (SqlConnection connection = new SqlConnection(ConnectionString))
            {
                SqlCommand cmd = BuildQueryCommand(connection, storeProcName, parameters);
                int rows = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                connection.Close();
                connection.Dispose();
                return rows;
            }
        }
        public Object RunProcedureGetSingle(string storeProcName, DbParameter[] parameters)
        {
            using (SqlConnection connection = new SqlConnection(ConnectionString))
            {
                SqlCommand cmd = BuildQueryCommand(connection, storeProcName, parameters);
                try
                {
                    object obj = cmd.ExecuteScalar();
                    cmd.Parameters.Clear();
                    if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                    {
                        return null;
                    }
                    else
                    {
                        return obj;
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                finally
                {
                    if (cmd != null)
                    {
                        cmd.Dispose();
                    }
                    if (connection != null)
                    {
                        connection.Close();
                        connection.Dispose();
                    }
                }
            }
        }
        public DbDataReader RunProcedureGetDataReader(string storedProcName, DbParameter[] parameters)
        {
            SqlConnection connection = new SqlConnection(ConnectionString);
            SqlDataReader returnReader;
            SqlCommand cmd = BuildQueryCommand(connection, storedProcName, parameters);
            cmd.CommandType = CommandType.StoredProcedure;
            returnReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            cmd.Parameters.Clear();
            return returnReader;
        }
        public DataSet RunProcedureGetDataSet(string storedProcName, DbParameter[] parameters)
        {
            using (SqlConnection connection = new SqlConnection(ConnectionString))
            {
                DataSet dataSet = new DataSet();
                connection.Open();
                SqlDataAdapter sqlDA = new SqlDataAdapter();
                sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
                sqlDA.Fill(dataSet);
                connection.Close();
                sqlDA.SelectCommand.Parameters.Clear();
                sqlDA.Dispose();
                return dataSet;
            }
        }
        public bool RunProcedureTran(Hashtable SQLStringList)
        {
            using (SqlConnection connection = new SqlConnection(ConnectionString))
            {
                connection.Open();
                using (SqlTransaction trans = connection.BeginTransaction())
                {
                    SqlCommand cmd = new SqlCommand();
                    try
                    {
                        //循环
                        foreach (DictionaryEntry myDE in SQLStringList)
                        {
                            cmd.Connection = connection;
                            string storeName = myDE.Value.ToString();
                            SqlParameter[] cmdParms = (SqlParameter[])myDE.Key;

                            cmd.Transaction = trans;
                            cmd.CommandText = storeName;
                            cmd.CommandType = CommandType.StoredProcedure;
                            if (cmdParms != null)
                            {
                                foreach (SqlParameter parameter in cmdParms)
                                    cmd.Parameters.Add(parameter);
                            }
                            int val = cmd.ExecuteNonQuery();
                            cmd.Parameters.Clear();
                        }
                        trans.Commit();
                        return true;
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        throw ex;
                    }

                    finally
                    {
                        if (cmd != null)
                        {
                            cmd.Dispose();
                        }
                        if (connection != null)
                        {
                            connection.Close();
                            connection.Dispose();
                        }
                    }
                }
            }
        }
        private SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, DbParameter[] parameters)
        {
            if (connection.State != ConnectionState.Open)
                connection.Open();
            SqlCommand command = new SqlCommand(storedProcName, connection);
            command.CommandType = CommandType.StoredProcedure;
            if (parameters != null)
            {
                foreach (SqlParameter parameter in parameters)
                {
                    command.Parameters.Add(parameter);
                }
            }
            return command;
        }
        #endregion

        #region 参数构造
        /// <summary>
        /// 传入输入参数
        /// </summary>
        /// <param name="ParamName">参数名称</param>
        /// <param name="DbType">参数类型</param>
        /// <param name="Size">参数大小</param>
        /// <param name="Value">参数值</param>
        /// <returns>新的parameter 对象</returns>
        public SqlParameter CreateInParam(string ParamName, SqlDbType DbType, int Size, object Value)
        {
            return CreateParam(ParamName, DbType, Size, ParameterDirection.Input, Value);
        }

        /// <summary>
        /// 生成SQL语句参数
        /// </summary>
        /// <param name="ParamName">参数名称</param>
        /// <param name="DbType">参数类型</param>
        /// <param name="Size">参数大小</param>
        /// <param name="Direction">参数方向</param>
        /// <param name="Value">参数值</param>
        /// <returns>新的 parameter 对象</returns>
        public SqlParameter CreateParam(string ParamName, SqlDbType DbType, Int32 Size, ParameterDirection Direction, object Value)
        {
            SqlParameter param;
            ///当参数大小为0时，不使用该参数大小值
            if (Size > 0)
            {
                param = new SqlParameter(ParamName, DbType, Size);
            }
            else
            {
                ///当参数大小为0时，不使用该参数大小值
                param = new SqlParameter(ParamName, DbType);
            }
            ///创建输出类型的参数
            param.Direction = Direction;
            if (!(Direction == ParameterDirection.Output && Value == null))
            {
                param.Value = Value;
            }
            ///返回创建的参数
            return param;
        }

        #endregion

        #region 测试数据库连接
        /// <summary>
        /// 测试连接数据库是否成功
        /// </summary>
        /// <returns></returns>
        public bool ConnectionTest()
        {
            bool IsCanConnectioned = false;
            using (SqlConnection connection = new SqlConnection(ConnectionString))
            {
                //ConnectionTimeout 在.net 1.x 可以设置 在.net 2.0后是只读属性，则需要在连接字符串设置
                //如：server=.;uid=sa;pwd=;database=PMIS;Integrated Security=SSPI; Connection Timeout=30

                //connection.ConnectionTimeout = 1;//设置连接超时的时间
                try
                {
                    //Open DataBase
                    //打开数据库
                    connection.Open();
                    IsCanConnectioned = true;
                }
                catch
                {
                    //Can not Open DataBase
                    //打开不成功 则连接不成功
                    IsCanConnectioned = false;
                }
                finally
                {
                    //Close DataBase
                    //关闭数据库连接
                    connection.Close();
                }
                //mySqlConnection   is   a   SqlConnection   object 
                if (connection.State == ConnectionState.Closed || connection.State == ConnectionState.Broken)
                {
                    //Connection   is   not   available  
                    return IsCanConnectioned;
                }
                else
                {
                    //Connection   is   available  
                    return IsCanConnectioned;
                }
            }

        }
        #endregion 测试数据库连接

    }
}
